package ar.edu.itba.pod.legajo48013.event;

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

import ar.edu.itba.event.EventInformation;
import ar.edu.itba.event.RemoteEventDispatcher;
import ar.edu.itba.node.Node;
import ar.edu.itba.node.NodeInformation;
import ar.edu.itba.pod.legajo48013.Utils;
import ar.edu.itba.pod.legajo48013.host.Host;
import ar.edu.itba.pod.legajo48013.rmi.LookupUtil;

public class EventThread extends Thread implements Remote{

	private Host host;
	
	public EventThread(Host host) {
		this.host = host;
	}
	
	@Override
	public void run() {
		try {
			while(true) {
				EventInformation event = host.getPendingEvents().take();
				
				ClusterEventDispatcher localDispatcher = host.getDispatcher();
				localDispatcher.publishLocal(event);

				host.getProcessedEvents().add(new ProcessedEvent(new Date().getTime(), event));
				
				Set<NodeInformation> copyNodesConnected = Utils.getCopyOfConnectedNodes(host);
				int initSize = copyNodesConnected.size();
				int falseSize = 0;
				
				Iterator<NodeInformation> it = copyNodesConnected.iterator();
				while (it.hasNext() && (falseSize*100/initSize<30)){
					NodeInformation node = it.next();
					if(!host.getNode().equals(node)){
						RemoteEventDispatcher dispatcher = (RemoteEventDispatcher) LookupUtil.lookup(host, node, Node.DISTRIBUTED_EVENT_DISPATCHER);
						if(dispatcher != null){
							falseSize += dispatcher.publish(event)?0:1;
							System.out.println("published event in node " + node.host() + ":" + node.port());
							host.getUpdates().put(node, new Date().getTime());
						}else{
							initSize--;
						}
	
					}
				}

			}
		}catch (InterruptedException e) {
			e.printStackTrace();
			//TODO what to to??
		} catch (RemoteException e) {
			e.printStackTrace();
			//TODO what to to??
		}
	}

}
